package com.base.commonlib.http.call;
import com.base.commonlib.http.NetWorkInitial;
import com.base.commonlib.http.ResponseT;
import com.base.commonlib.http.utils.ParameterizedTypeImpl;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Date：2019/3/29 下午3:17
 * Creator：arvin
 * Des：
 */

public class DataSynRequestCall extends BaseSynRequestCall {
    protected Call<String> call;

    public DataSynRequestCall(Call<String> call) {
        this.call = call;
    }

    public <T> T execute(Class<T> clazz) throws Exception {
        Response<String> execute = call.execute();
        String body = NetWorkInitial.customDecode(execute);
        ParameterizedTypeImpl type = new ParameterizedTypeImpl(ResponseT.class, new Class[]{clazz});
        Gson gson = new Gson();
        ResponseT<T> responseT = gson.fromJson(body, type);
        if (responseT.isSuccess()) {
            return responseT.getData();
        } else {
            throw new Exception(responseT.getMsg());
        }

    }

    public <T> List<T> executeForArray(Class<List<T>> clazz) throws Exception {
        Response<String> execute = call.execute();
        String body = NetWorkInitial.customDecode(execute);
        ParameterizedTypeImpl type_list = new ParameterizedTypeImpl(List.class, new Class[]{clazz});
        ParameterizedTypeImpl type = new ParameterizedTypeImpl(ResponseT.class, new Type[]{type_list});
        Gson gson = new Gson();
        ResponseT<List<T>> responseT = gson.fromJson(body, type);
        if (responseT.isSuccess()) {
            return responseT.getData();
        } else {
            throw new Exception(responseT.getMsg());
        }

    }
}
